package client;

import java.io.DataOutputStream;
import java.util.ArrayList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

import event.Event;
import event.EventHandler;

public class EventManager<T extends Event, S extends EventHandler> implements
		Runnable {

	private final ArrayList<S> mHandlers = new ArrayList<S>();
	private final PriorityBlockingQueue<T> mQueue = new PriorityBlockingQueue<T>();

	public EventManager() {

	}

	/**
	 * Place items in the queue.
	 * 
	 * @param item
	 */
	public void put(T item) {
		mQueue.put(item);
	}

	@Override
	public void run() {
		try {
			for (;;) {
				T item = mQueue.take();

				System.out.println("> EVENT MANAGER: Handling event.");
				
				handle(item);
			}
		} catch (InterruptedException e) {
			System.out.println("Event manager stopped.");
		}
	}

	public void handle(T item) {
		for (S handler : mHandlers) {
			handler.handle(item);
		}
	}

	public void register(S handler) {
		mHandlers.add(handler);
	}

	public void unregister(S handler) {
		mHandlers.remove(handler);
	}

}
